/**
 * Created by WLG on 2018/11/6.
 */
//require('./lib/kaiguang');
let koa = require('koa');
//跨域
let cors = require('koa2-cors');
//请求解析 涉及 post 与 文件上传
let koaBody = require('koa-body');
//对象存储
let ObsManager = require('./lib/obsManager');

let app = new koa();
let server = require('http').createServer(app);
let io = require('socket.io')(server,{
    "serveClient": false ,
    "transports":['websocket', 'polling']
});

let serverConfig = require('./config/serverConfig');

let log4js = require("log4js");
let logConfig = require("./config/logConf");
log4js.configure(logConfig);
//全局 三兄弟^_^
global.logInfo = log4js.getLogger();
global.logError = log4js.getLogger("error_log");
global.commonUtil = require('./lib/commonUtil');

let DatabaseManager = require("./lib/databaseManager");
let redisDB = require("./lib/redisManage");
let ChatServer = require('./chatServer');

//监听 http 服务端口
app.listen(serverConfig.httpPort);
//监听 socket 服务端口
server.listen(serverConfig.socketPort);
//会话服务
let tocChatServer = new ChatServer();
//附件上传
app.use(koaBody(
    {
        multipart: true,
        formidable: {
            maxFileSize: 200*1024*1024    // 设置上传文件大小最大限制，默认2M
        }
    }
));
//跨域
app.use(cors({
    origin: function (ctx) {
        return "*";
    },
    exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
    maxAge: 5,
    credentials: false,
    allowMethods: ['GET', 'POST', 'DELETE'],
    allowHeaders: ['*'],
}));
//异常日志
app.use(
    async (ctx, next) => {
        try {
            await next();
        } catch (error) {
            logError.error('server error', error, ctx)
        }
    }
);
/*app.on('error', (err, ctx) => {
    logError.error('server error', err, ctx)
});*/
//由链接数据库开始启动
DatabaseManager.init().once('open',async function(){
    commonUtil.consoleSysInfo("Mongodb初始化完成");
    //初始化聊天服务
    tocChatServer.init(app,io,serverConfig);
    //初始化OBS
    ObsManager.init();
});